<template>
  <view class="page-container">
    <S1Header title="欠款列表" :on-back="onBack" />

    <view class="content-container">
      <view class="flex items-center bg-white px-20rpx py-12rpx">
        <view class="relative h-80rpx flex flex-1 items-center rounded-full bg-[#f5f5f5] px-20rpx">
          <image src="https://ceshiweb.picaime.com/static/images/search.png" class="mr-10rpx h-40rpx w-40rpx" />
          <input
            v-model="keyword" class="flex-1 text-30rpx" placeholder="搜索买家名称或手机号" confirm-type="search"
            @confirm="onSearch"
          >
          <view
            v-if="keyword" class="absolute right-20rpx h-44rpx w-44rpx flex items-center justify-center"
            @click="clearKeyword"
          >
            <image class="h-40rpx w-40rpx" src="https://ceshiweb.picaime.com/static/images/close.png" />
          </view>
        </view>
        <view class="ml-16rpx h-44rpx w-44rpx flex items-center justify-center" @click="toggleFilter">
          <image class="h-40rpx w-40rpx" src="https://ceshiweb.picaime.com/static/images/filter.png" />
        </view>
      </view>

      <view class="flex items-center justify-between bg-[#f5f5f5] px-20rpx py-20rpx">
        <text class="text-28rpx text-[#333]">
          总赊欠：
          <text class="text-[#FF6B01] font-bold">
            {{ formatNumber(totalOwe) }}
          </text>
          ，共{{ total_num }}人赊欠
        </text>
        <view class="flex items-center text-28rpx text-[#007aff]" @click="onCollectionDoc">
          <image src="https://ceshiweb.picaime.com/static/images/pyq.png" class="mr-4rpx h-32rpx w-32rpx" />
          <text>赊账打印</text>
        </view>
      </view>

      <scroll-view
        class="buyer-list" scroll-y :scroll-with-animation="true" @scrolltolower="onLoadMore"
        @pull-down-refresh="onPullDown"
      >
        <view
          v-for="(buyer, index) in buyers" :key="index"
          class="relative border-b-1rpx border-b-[#f5f5f5] border-b-solid bg-white p-20rpx"
          @click="goDetail(buyer)"
        >
          <view class="absolute right-20rpx top-20rpx" @click.stop>
            <button
              :id="`share-btn-${index}`"
              class="share-button h-66rpx w-148rpx flex items-center justify-center rounded-6rpx border-none bg-[rgba(67,207,124,1)] outline-none"
              :class="{ 'opacity-60': buyer.isGeneratingImage }"
              open-type="share"
              :data-buyer-index="index"
            >
              <image
                v-if="!buyer.isGeneratingImage" class="mr-6rpx h-26rpx w-26rpx"
                src="https://ceshiweb.picaime.com/static/images/share.png"
              />
              <text class="text-30rpx text-white font-400">
                {{ buyer.isGeneratingImage ? '生成中...' : '分享' }}
              </text>
            </button>
          </view>

          <view class="mb-6rpx flex items-center pr-160rpx">
            <text class="text-40rpx text-black font-400 tracking-0">
              {{ buyer.maijia }}
            </text>
            <text v-if="buyer.phone" class="ml-10rpx text-30rpx text-[#999]">
              {{ buyer.phone }}
            </text>
          </view>

          <view class="mb-6rpx flex items-center">
            <text class="text-30rpx text-[#999]">
              赊欠限制：
            </text>
            <text class="text-30rpx text-[#999]">
              {{ buyer.max_zhang_money || '未限制' }}
            </text>
            <view v-if="buyer.limitDay" class="ml-10rpx rounded-[4rpx] bg-[#e5e5e5] px-16rpx py-4rpx text-white">
              <text class="text-26rpx">
                {{ buyer.limitDay }}天
              </text>
            </view>
            <text class="ml-10rpx text-30rpx text-[#666]">
              最大赊欠：{{ buyer.max_zhang_day || '未限制' }}天
            </text>
          </view>

          <view class="flex items-center justify-between">
            <view class="flex items-center">
              <template v-if="Number(buyer.sheqian_total) > 0">
                <text class="text-30rpx text-[#999]">
                  已赊欠：
                </text>
                <text class="text-40rpx text-[#FF6B01] font-bold">
                  {{ formatNumber(buyer.sheqian_total) }}元
                </text>
                <view
                  class="ml-10rpx rounded-4rpx px-10rpx py-2rpx"
                  :class="Number(buyer.sheqian_day) > 30 ? 'bg-[#ffefef] text-[#ff4949]' : 'bg-[#e8f9ef] text-[#43CF7C]'"
                >
                  <text class="text-26rpx">
                    {{ buyer.sheqian_day }}天
                  </text>
                </view>
              </template>
            </view>
            <view class="flex items-center">
              <text class="mr-6rpx text-30rpx text-[#999]">
                详情
              </text>
              <image class="h-32rpx w-32rpx" src="https://ceshiweb.picaime.com/static/images/report/right.png" />
            </view>
          </view>
        </view>
      </scroll-view>

      <!-- Canvas 画布用于绘制分享图片 -->
      <canvas

        canvas-id="shareCanvas"
        :style="{
          width: `${canvasWidth}px`,
          height: `${canvasHeight}px`,
          position: 'fixed',
          right: '-999999px',
        }"
      />

      <view v-if="showFilter" class="fixed inset-0 z-999 bg-black bg-opacity-40" @click.self="toggleFilter" />
      <transition name="slide-up">
        <view v-if="showFilter" class="fixed bottom-0 left-0 right-0 z-1000 rounded-t-20rpx bg-white shadow-md">
          <view
            class="mx-auto mt-10rpx h-60rpx w-60rpx bg-contain bg-center bg-no-repeat"
            style="background-image: url('https://ceshiweb.picaime.com/static/images/arrow-double-down.png');"
            @click="toggleFilter"
          />
          <view class="p-20rpx">
            <view class="my-10rpx flex items-center">
              <view class="mr-10rpx h-32rpx w-6rpx rounded-2rpx bg-[#07c160]" />
              <text>排序</text>
            </view>
            <view class="mb-20rpx">
              <view
                v-for="(sortItem, idx) in sortList"
                :key="idx" class="sort-card mb-20rpx flex items-center justify-between rounded-8rpx p-20rpx shadow-sm"
                :class="currentSort === idx ? 'bg-[#43cf7c]' : 'bg-white'"
                @click="selectSort(idx)"
              >
                <text class="text-24rpx text-[#333]">
                  {{ sortItem }}
                </text>
                <image
                  v-if="currentSort === idx" class="ml-10rpx h-26rpx w-26rpx"
                  src="https://ceshiweb.picaime.com/static/images/check.png"
                />
              </view>
            </view>

            <view class="my-10rpx flex items-center">
              <view class="mr-10rpx h-32rpx w-6rpx rounded-2rpx bg-[#007aff]" />
              <text>筛选</text>
            </view>
            <view
              v-for="(option, i) in filterOptions" :key="i"
              class="filter-row mb-20rpx flex items-center justify-between"
            >
              <text class="text-24rpx text-[#333]">
                {{ option.label }}
              </text>
              <view class="flex">
                <view
                  v-for="(btn, j) in option.btns" :key="j"
                  class="ml-20rpx border border-[#07c160] rounded-6rpx px-14rpx py-4rpx text-24rpx"
                  :class="btn.active ? 'bg-[#07c160] text-white' : 'text-[#07c160] bg-white'"
                  @click="toggleOption(i, j)"
                >
                  {{ btn.text }}
                </view>
              </view>
            </view>
            <view class="mt-20rpx flex justify-between">
              <button
                class="w-45% border border-[#ff8c00] rounded-8rpx bg-white py-12rpx text-24rpx text-[#ff8c00]"
                @click="onReset"
              >
                重置
              </button>
              <button
                class="w-45% rounded-8rpx bg-[#07c160] py-12rpx text-24rpx text-white"
                @click="onConfirm"
              >
                确定
              </button>
            </view>
          </view>
        </view>
      </transition>
    </view>
  </view>
</template>

<script setup lang="ts">
import type { MemberItem, MemberListsReq } from '@/api/member/types';
import { onShareAppMessage } from '@dcloudio/uni-app';
import { onMounted, ref, watch } from 'vue';
import { getMemberLists } from '@/api/member';
import * as S1Header from '@/components/S1Header.vue';
import { useUserStore } from '@/store';

const userStore = useUserStore();

interface Buyer extends MemberItem {
  phone?: string;
  oweLimit?: number | string;
  limitDay?: number | string;
  oweDays?: number;
  shareImageUrl?: string; // 分享图片路径
  isGeneratingImage?: boolean; // 是否正在生成图片
}

const keyword = ref('');
const totalOwe = ref(0);
const total_num = ref(0);
const buyers = ref<Buyer[]>([]);

// 分享相关
const canvasShow = ref(false);
const canvasWidth = ref(375);
const canvasHeight = ref(300);
const currentShareBuyerIndex = ref(-1);

// 买家状态筛选 (对应源文件的 options_maijia_status_value)
// '0': 全部买家, '1': 停用买家
const options_maijia_status_value = ref('999'); // 默认全部买家

// 分页相关
const pages = ref({
  total: 0,
  currPage: 1,
  limit: 10,
});

// 加载状态
const loading = ref(false);
const loading2 = ref(false);
const finished = ref(false);

// 筛选选项
const options_order_status = ref([
  { value: '1', label: '按照赊欠金额最小' },
  { value: '2', label: '按照赊欠金额最大' },
  { value: '3', label: '按照赊欠时间最短' },
  { value: '4', label: '按照赊欠时间最长' },
  { value: '5', label: '按照消费时间长' },
  { value: '6', label: '按照消费时间短' },
  { value: '7', label: '按照消费总金额大' },
  { value: '8', label: '按照消费总金额小' },
]);

const options_order_status_value = ref('2'); // 默认按赊欠金额最大排序

const showFilter = ref(false);
const sortList = ref([
  '按赊欠金额从大到小',
  '按赊欠金额从小到大',
  '按赊欠时间从长到短',
  '按赊欠时间从短到长',
  '按消费时间从长到短',
  '按消费时间从短到长',
  '按消费金额从大到小',
  '按消费金额从小到大',
]);
const currentSort = ref(0);
const filterOptions = ref([
  {
    label: '买家状态',
    btns: [
      { text: '全部买家', active: true }, // '0' 或 '999'
      { text: '停用买家', active: false }, // '1'
    ],
  },
]);

// 页面加载时获取数据
onMounted(() => {
  // 初始化 canvas 尺寸
  uni.getSystemInfo({
    success: (res) => {
      canvasWidth.value = res.screenWidth;
      canvasHeight.value = res.screenWidth * 0.8; // 保持 5:4 比例
    },
  });

  onRefresh();
});

// 监听搜索关键词
watch(keyword, () => {
  onRefresh();
});

// 监听排序选项变化
watch(options_order_status_value, () => {
  onRefresh();
});

// API 数据获取函数
const getMemberListData = async () => {
  try {
    const params: MemberListsReq = {
      options_order_status_value: options_order_status_value.value,
      options_maijia_status_value: options_maijia_status_value.value,
      keywords: keyword.value,
      page: pages.value.currPage,
      limit: pages.value.limit,
    };

    const res = await getMemberLists(params);
    if (res.code === 200) {
      const newData = res.data.data.data;

      if (pages.value.currPage === 1) {
        buyers.value = newData;
      }
      else {
        buyers.value = [...buyers.value, ...newData];
      }

      totalOwe.value = res.data.total_price || 0;
      total_num.value = res.data.total_num || 0;
      pages.value.total = res.data.data.total;

      if (buyers.value.length >= pages.value.total) {
        finished.value = true;
      }

      loading.value = false;
      loading2.value = false;
    }
    else {
      uni.showToast({
        title: res.msg || '获取数据失败',
        icon: 'none',
      });
    }
  }
  catch (error) {
    console.error('获取会员列表失败:', error);
    uni.showToast({
      title: '网络错误',
      icon: 'none',
    });
  }
};

// 下拉刷新
const onPullDown = () => {
  pages.value.currPage = 1;
  finished.value = false;
  getMemberListData();
};

// 加载更多
const onLoadMore = () => {
  if (!finished.value && !loading2.value) {
    loading2.value = true;
    pages.value.currPage++;
    getMemberListData();
  }
};

// 刷新数据
const onRefresh = () => {
  pages.value.currPage = 1;
  finished.value = false;
  buyers.value = [];
  getMemberListData();
};

function onBack() {
  uni.navigateBack();
}

// 赊账打印
function onCollectionDoc() {
  // TODO: 根据实际打印需求实现
  // 参考源文件：sheqian_printer(this.tableData, this.total_price, this.total_num)
  console.log('赊账打印', {
    buyers: buyers.value,
    totalOwe: totalOwe.value,
    total_num: total_num.value,
  });

  uni.showToast({
    title: '赊账打印功能开发中',
    icon: 'none',
  });
}

function onSearch() {
  onRefresh();
}

function toggleFilter() {
  showFilter.value = !showFilter.value;
}

function formatNumber(num: number | string) {
  return Number(num).toLocaleString();
}

function formatDate(date: Date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

function selectSort(idx: number) {
  currentSort.value = idx;
  // 映射排序索引到 options_order_status_value
  const sortValueMap = ['2', '1', '4', '3', '5', '6', '7', '8'];
  options_order_status_value.value = sortValueMap[idx];
}

function toggleOption(i: number, j: number) {
  // 创建新对象确保响应式更新
  filterOptions.value = filterOptions.value.map((option, optionIndex) => {
    if (optionIndex === i) {
      return {
        ...option,
        btns: option.btns.map((btn, btnIndex) => ({
          ...btn,
          active: btnIndex === j,
        })),
      };
    }
    return option;
  });
}

function onReset() {
  currentSort.value = 0;
  // 重置排序为默认（按赊欠金额从大到小）
  options_order_status_value.value = '2';

  // 重置筛选条件
  filterOptions.value = filterOptions.value.map(option => ({
    ...option,
    btns: option.btns.map((btn, idx) => ({ ...btn, active: idx === 0 })),
  }));

  // 重置买家状态为全部买家
  options_maijia_status_value.value = '999';
}

function onConfirm() {
  showFilter.value = false;

  // 应用排序设置
  const sortValueMap = ['2', '1', '4', '3', '5', '6', '7', '8'];
  options_order_status_value.value = sortValueMap[currentSort.value];

  // 应用买家状态筛选
  // filterOptions[0] -> 买家状态
  if (filterOptions.value[0].btns[0].active) {
    options_maijia_status_value.value = '999'; // 全部买家
  }
  else if (filterOptions.value[0].btns[1].active) {
    options_maijia_status_value.value = '1'; // 停用买家
  }

  console.log('应用筛选:', {
    排序: sortList.value[currentSort.value],
    排序值: options_order_status_value.value,
    买家状态值: options_maijia_status_value.value,
    筛选条件: filterOptions.value,
  });

  // 刷新数据
  onRefresh();
}

function clearKeyword() {
  keyword.value = '';
  onSearch();
}

// 跳转到详情页
function goDetail(buyer: Buyer) {
  // TODO: 跳转到买家详情页面
  console.log('查看详情:', buyer);
  uni.navigateTo({
    url: `/pages/common/creditOrderList/creditOrderList?maijia_id=${buyer.maijia_id}&maijia=${buyer.maijia}`,
  });
}

// 创建分享图片（返回 Promise）
function createShareImage(buyer: Buyer, index: number): Promise<string> {
  return new Promise((resolve, reject) => {
    // 显示 canvas 画布
    canvasShow.value = true;

    // 获取 canvas 实例
    // @ts-ignore
    const ctx = uni.createCanvasContext('shareCanvas');

    // 设置背景色
    ctx.setFillStyle('#f5fafe');
    ctx.fillRect(0, 0, canvasWidth.value, canvasHeight.value);

    // 添加边框
    ctx.setStrokeStyle('#f0f0f0');
    ctx.setLineWidth(1);
    ctx.strokeRect(0, 0, canvasWidth.value, canvasHeight.value);

    // 绘制买家名称（标题）- 加粗效果
    ctx.setFillStyle('#000000');
    ctx.setFontSize(36);
    ctx.setTextAlign('left');
    // 多次绘制模拟加粗
    ctx.fillText(buyer.maijia, 29, 60);
    ctx.fillText(buyer.maijia, 29.5, 60);
    ctx.fillText(buyer.maijia, 29, 60.5);
    ctx.fillText(buyer.maijia, 29.5, 60.5);

    // 绘制副标题 "赊欠金额" - 字体较大
    ctx.setFillStyle('#999999');
    ctx.setFontSize(24);
    ctx.fillText('赊欠金额', 30, 100);

    // 绘制订单数 "(X单)" - 字体较小，并留有间距
    const labelWidth = ctx.measureText('赊欠金额').width;
    ctx.setFontSize(20);
    ctx.fillText(`(${buyer.no_pay_num}单)`, 30 + labelWidth + 8, 100);

    // 绘制手机号（如果有）
    if (buyer.phone) {
      ctx.setFillStyle('#999999');
      // 计算"赊欠金额"宽度
      ctx.setFontSize(24);
      const labelWidth2 = ctx.measureText('赊欠金额').width;
      // 计算"(X单)"宽度
      ctx.setFontSize(20);
      const unitWidth = ctx.measureText(`(${buyer.no_pay_num}单)`).width;
      // 设置手机号字体大小
      ctx.setFontSize(18);
      ctx.fillText(`（${buyer.phone}）`, 30 + labelWidth2 + 8 + unitWidth + 10, 100);
    }

    // 绘制金额（大号绿色）- 加粗效果
    ctx.setFillStyle('#3abe2c');
    ctx.setFontSize(48);
    ctx.setTextAlign('left');
    const amountText = `¥${formatNumber(buyer.sheqian_total)}`;
    // 多次绘制模拟加粗
    ctx.fillText(amountText, 30, 160);
    ctx.fillText(amountText, 30.5, 160);
    ctx.fillText(amountText, 30, 160.5);
    ctx.fillText(amountText, 30.5, 160.5);

    // 计算日期范围（假设从当前日期往前推 sheqian_day 天）
    const endDate = new Date();
    const startDate = new Date();
    startDate.setDate(endDate.getDate() - Number(buyer.sheqian_day || 0));
    const dateRange = `${formatDate(startDate)} 至 ${formatDate(endDate)}`;

    // 绘制日期范围
    ctx.setFillStyle('#666666');
    ctx.setFontSize(18);
    ctx.fillText(dateRange, 30, 200);

    // 绘制底部绿色渐变按钮区域（带圆角）
    const btnX = 30;
    const btnY = canvasHeight.value - 70;
    const btnWidth = canvasWidth.value - 60;
    const btnHeight = 50;
    const btnRadius = 2;

    // 绘制圆角矩形
    ctx.beginPath();
    ctx.moveTo(btnX + btnRadius, btnY);
    ctx.lineTo(btnX + btnWidth - btnRadius, btnY);
    ctx.arcTo(btnX + btnWidth, btnY, btnX + btnWidth, btnY + btnRadius, btnRadius);
    ctx.lineTo(btnX + btnWidth, btnY + btnHeight - btnRadius);
    ctx.arcTo(btnX + btnWidth, btnY + btnHeight, btnX + btnWidth - btnRadius, btnY + btnHeight, btnRadius);
    ctx.lineTo(btnX + btnRadius, btnY + btnHeight);
    ctx.arcTo(btnX, btnY + btnHeight, btnX, btnY + btnHeight - btnRadius, btnRadius);
    ctx.lineTo(btnX, btnY + btnRadius);
    ctx.arcTo(btnX, btnY, btnX + btnRadius, btnY, btnRadius);
    ctx.closePath();

    // 填充渐变色（135度,从青绿到草绿）
    const gradient = ctx.createLinearGradient(btnX, btnY, btnX + btnWidth, btnY + btnHeight);
    gradient.addColorStop(0.2, '#009481'); // 青绿色（20%）
    gradient.addColorStop(1, '#52b316'); // 草绿色（100%）
    ctx.setFillStyle(gradient);
    ctx.fill();

    // 绘制按钮文字
    ctx.setFillStyle('#ffffff');
    ctx.setFontSize(20);
    ctx.setTextAlign('center');
    ctx.fillText('查看订单详情', canvasWidth.value / 2, btnY + btnHeight / 2 + 6);

    // 绘制完成后，生成图片
    ctx.draw(false, () => {
      setTimeout(() => {
        uni.canvasToTempFilePath({
          canvasId: 'shareCanvas',
          success: (res) => {
            console.log('分享图片生成成功:', res.tempFilePath);
            // 直接使用临时文件路径（微信分享支持临时路径）
            buyers.value[index].shareImageUrl = res.tempFilePath;
            buyers.value[index].isGeneratingImage = false;
            resolve(res.tempFilePath);
          },
          fail: (err) => {
            console.error('生成图片失败:', err);
            buyers.value[index].isGeneratingImage = false;
            reject(err);
          },
          complete: () => {
            // 隐藏 canvas
            canvasShow.value = false;
          },
        });
      }, 300); // 延迟确保绘制完成
    });
  });
}

// 注册分享方法（微信小程序专用）
// 支持异步返回 Promise
onShareAppMessage(async (options: any) => {
  // 从 button 的 dataset 中获取买家索引
  if (options.from === 'button' && typeof options.target?.dataset?.buyerIndex !== 'undefined') {
    const buyerIndex = Number(options.target.dataset.buyerIndex);
    const buyer = buyers.value[buyerIndex];

    if (!buyer) {
      return {
        title: '欠款提醒',
        path: '/pages/tab/list/debt',
      };
    }

    // 显示 loading
    uni.showLoading({
      title: '正在生成分享图片...',
      mask: true,
    });

    // 标记正在生成
    buyers.value[buyerIndex].isGeneratingImage = true;

    try {
      // 等待图片生成完成
      const imagePath = await createShareImage(buyer, buyerIndex);

      uni.hideLoading();

      // 目标小程序的 appId 和路径
      const targetAppId = 'wx26980c7935e571cc';
      // 获取档口ID（店铺ID）从 userStore，如果没有则使用 userInfo.admin_id
      const storeId = userStore.userInfo?.admin_id || '';
      const storeName = encodeURIComponent(userStore.dangkou_name || '云批宝');
      const username = encodeURIComponent(userStore.user_name || '');

      // 构建小程序页面路径：传递 storeId, storeName, username, maijia_id（用于过滤）
      const targetPath = encodeURIComponent(`pages/reconciliation/reconciliation?storeId=${storeId}&storeName=${storeName}&username=${username}&maijia_id=${buyer.maijia_id}`);

      // 返回分享配置
      return {
        title: `${userStore.real_name || '商家'}`,
        path: `/pages/common/share/redirect?targetAppId=${targetAppId}&targetPath=${targetPath}&maijia=${encodeURIComponent(buyer.maijia)}&amount=${buyer.sheqian_total || 0}&days=${buyer.sheqian_day || 0}&phone=${buyer.phone || ''}&shopName=${storeName}`,
        imageUrl: imagePath,
        miniProgram: {
          id: 'wx26980c7935e571cc',
          path: targetPath,
          // 可选：指定小程序版本类型（正式版/体验版）
          envVersion: 'trial',
        },
      };
    }
    catch (error) {
      uni.hideLoading();
      uni.showToast({
        title: '生成图片失败',
        icon: 'none',
      });
    }
  }

  // 默认分享内容
  console.log('❌ 使用默认分享');
  return {
    title: '欠款提醒',
    path: '/pages/tab/list/debt',
  };
});
</script>

<style scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.content-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.buyer-list {
  flex: 1;
  overflow-y: auto;
}

/* 动画 */
.slide-up-enter-active,
.slide-up-leave-active {
  transition: transform 0.3s ease-in-out;
}

.slide-up-enter {
  transform: translateY(100%);
}

.slide-up-leave-to {
  transform: translateY(100%);
}
</style>
